import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { toast } from 'sonner';
import { useTheme } from '@/hooks/useTheme';
import { cn } from '@/lib/utils';

// 用户角色类型
type UserRole = 'student' | 'admin' | 'merchant' | 'all';

// 用户状态类型
type UserStatus = 'active' | 'inactive' | 'all';

// 用户接口
interface User {
  id: string;
  username: string;
  role: 'student' | 'admin' | 'merchant';
  email: string;
  phone: string;
  campus: string;
  status: 'active' | 'inactive';
  joinDate: string;
  lastLogin: string;
  avatar?: string;
  transactionCount: number;
  rating: number;
}

// 模拟用户数据
const mockUsers: User[] = [
  {
    id: '1',
    username: 'student1',
    role: 'student',
    email: 'student1@example.com',
    phone: '138****1234',
    campus: '主校区',
    status: 'active',
    joinDate: '2023-09-01',
    lastLogin: '2023-10-30 10:30:00',
    avatar: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=male%20college%20student%20avatar&sign=ce2e40061e9899bed92d3bab0ea79407',
    transactionCount: 12,
    rating: 4.8
  },
  {
    id: '2',
    username: 'admin',
    role: 'admin',
    email: 'admin@example.com',
    phone: '139****5678',
    campus: '主校区',
    status: 'active',
    joinDate: '2023-08-15',
    lastLogin: '2023-10-30 09:15:00',
    avatar: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=male%20admin%20avatar&sign=17f36fdfe029e2f5d0ab5a9a0d59b0dc',
    transactionCount: 0,
    rating: 0
  },
  {
    id: '3',
    username: 'merchant1',
    role: 'merchant',
    email: 'merchant1@example.com',
    phone: '137****9012',
    campus: '东校区',
    status: 'active',
    joinDate: '2023-09-10',
    lastLogin: '2023-10-29 16:45:00',
    avatar: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=business%20merchant%20avatar&sign=9f98bde0b3071f9a1ff4c6dd01880fb0',
    transactionCount: 56,
    rating: 4.9
  },
  {
    id: '4',
    username: 'student2',
    role: 'student',
    email: 'student2@example.com',
    phone: '136****3456',
    campus: '西校区',
    status: 'inactive',
    joinDate: '2023-09-05',
    lastLogin: '2023-10-15 14:20:00',
    avatar: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=female%20college%20student%20avatar&sign=b97f59b3a9064405032318a3e1b91a73',
    transactionCount: 8,
    rating: 4.7
  },
  {
    id: '5',
    username: 'student3',
    role: 'student',
    email: 'student3@example.com',
    phone: '135****7890',
    campus: '南校区',
    status: 'active',
    joinDate: '2023-09-20',
    lastLogin: '2023-10-28 11:30:00',
    avatar: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=male%20college%20student%20avatar&sign=ce2e40061e9899bed92d3bab0ea79407%202',
    transactionCount: 5,
    rating: 4.6
  },
  {
    id: '6',
    username: 'merchant2',
    role: 'merchant',
    email: 'merchant2@example.com',
    phone: '134****2345',
    campus: '北校区',
    status: 'active',
    joinDate: '2023-10-01',
    lastLogin: '2023-10-30 08:45:00',
    avatar: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=female%20business%20merchant%20avatar&sign=2d93e8b329333750bb52714cc44b7289',
    transactionCount: 32,
    rating: 4.8
  }
];

export default function Users() {
  const [users, setUsers] = useState<User[]>([]);
  const [filteredUsers, setFilteredUsers] = useState<User[]>([]);
  const [selectedRole, setSelectedRole] = useState<UserRole>('all');
  const [selectedStatus, setSelectedStatus] = useState<UserStatus>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(10);
  const [isLoading, setIsLoading] = useState(true);
  const { theme } = useTheme();

  // 加载用户数据
  useEffect(() => {
    // 模拟API请求
    setTimeout(() => {
      setUsers(mockUsers);
      setFilteredUsers(mockUsers);
      setIsLoading(false);
    }, 1000);
  }, []);

  // 筛选用户
  useEffect(() => {
    let filtered = [...users];
    
    // 按角色筛选
    if (selectedRole !== 'all') {
      filtered = filtered.filter(user => user.role === selectedRole);
    }
    
    // 按状态筛选
    if (selectedStatus !== 'all') {
      filtered = filtered.filter(user => user.status === selectedStatus);
    }
    
    // 按搜索关键词筛选
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(user => 
        user.username.toLowerCase().includes(query) || 
        user.email.toLowerCase().includes(query) ||
        user.phone.toLowerCase().includes(query) ||
        user.campus.toLowerCase().includes(query)
      );
    }
    
    setFilteredUsers(filtered);
    setCurrentPage(1); // 重置到第一页
  }, [selectedRole, selectedStatus, searchQuery, users]);

  // 计算分页
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = filteredUsers.slice(indexOfFirstItem, indexOfLastItem);
  const totalPages = Math.ceil(filteredUsers.length / itemsPerPage);

  // 改变用户状态
  const changeUserStatus = (userId: string, newStatus: 'active' | 'inactive') => {
    if (userId === '2') { // 假设ID为2的是超级管理员，不能禁用
      toast.warning('超级管理员账号不能禁用');
      return;
    }
    
    const updatedUsers = users.map(user => 
      user.id === userId ? { ...user, status: newStatus } : user
    );
    setUsers(updatedUsers);
    toast.success(`用户状态已更新为${newStatus === 'active' ? '启用' : '禁用'}`);
  };

  // 删除用户
  const deleteUser = (userId: string) => {
    if (userId === '2') { // 假设ID为2的是超级管理员，不能删除
      toast.warning('超级管理员账号不能删除');
      return;
    }
    
    if (window.confirm('确定要删除该用户吗？此操作不可恢复。')) {
      const updatedUsers = users.filter(user => user.id !== userId);
      setUsers(updatedUsers);
      toast.success('用户已删除');
    }
  };

  // 角色样式映射
  const roleStyles = {
    'student': { text: '学生', className: 'px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300' },
    'admin': { text: '管理员', className: 'px-2 py-1 text-xs font-medium rounded-full bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300' },
    'merchant': { text: '商家', className: 'px-2 py-1 text-xs font-medium rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300' }
  };

  // 状态样式映射
  const statusStyles = {
    'active': { text: '启用', className: 'px-2 py-1 text-xs font-medium rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300' },
    'inactive': { text: '禁用', className: 'px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300' }
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className={cn("min-h-screen bg-gray-50 dark:bg-gray-900")}>
      {/* 顶部导航 */}
      <header className="bg-white dark:bg-gray-800 shadow-sm sticky top-0 z-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center">
              <Link to="/admin" className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 mr-4">
                <i className="fa-solid fa-arrow-left"></i>
              </Link>
              <h1 className="text-xl font-bold text-gray-900 dark:text-white">用户管理</h1>
            </div>
            
            <div className="flex items-center">
              <span className="text-sm text-gray-600 dark:text-gray-400 mr-4">欢迎，管理员</span>
              <div className="w-8 h-8 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
                <i className="fa-solid fa-user-shield text-gray-600 dark:text-gray-300"></i>
              </div>
            </div>
          </div>
        </div>
      </header>
      
      {/* 主体内容 */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 筛选和搜索 */}<div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 mb-6">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1">
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <i className="fa-solid fa-search text-gray-400"></i>
                </div>
                <input
                  type="text"
                  placeholder="搜索用户名、邮箱、手机号或校区..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="block w-full pl-10 pr-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-900 placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                />
              </div>
            </div>
            
            <div className="flex gap-4">
              <select
                value={selectedRole}
                onChange={(e) => setSelectedRole(e.target.value as UserRole)}
                className="block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              >
                <option value="all">全部角色</option>
                <option value="student">学生</option>
                <option value="admin">管理员</option>
                <option value="merchant">商家</option>
              </select>
              
              <select
                value={selectedStatus}
                onChange={(e) => setSelectedStatus(e.target.value as UserStatus)}
                className="block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              >
                <option value="all">全部状态</option>
                <option value="active">启用</option>
                <option value="inactive">禁用</option>
              </select>
            </div>
          </div>
        </div>
        
        {/* 用户列表 */}
        <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden border border-gray-200 dark:border-gray-700">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
              <thead className="bg-gray-50 dark:bg-gray-750">
                <tr>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    用户信息
                  </th>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    角色
                  </th>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    邮箱
                  </th>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    手机号
                  </th>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    校区
                  </th>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    注册时间
                  </th>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    最近登录
                  </th>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    交易情况
                  </th>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    状态
                  </th>
                  <th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                {currentItems.map((user) => (
                  <tr key={user.id} className="hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center">
                        <div className="flex-shrink-0 h-12 w-12">
                          {user.avatar ? (
                            <img 
                              className="h-12 w-12 rounded-full object-cover" 
                              src={user.avatar} 
                              alt={user.username}
                            />
                          ) : (
                            <div className="h-12 w-12 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center">
                              <i className="fa-solid fa-user text-gray-400"></i>
                            </div>
                          )}
                        </div>
                        <div className="ml-4">
                          <div className="text-sm font-medium text-gray-900 dark:text-gray-100">
                            {user.username}
                          </div>
                          <div className="text-xs text-gray-500 dark:text-gray-400">
                            ID: {user.id}
                          </div>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={roleStyles[user.role].className}>
                        {roleStyles[user.role].text}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900 dark:text-gray-100">{user.email}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900 dark:text-gray-100">{user.phone}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900 dark:text-gray-100">{user.campus}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                      {user.joinDate}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                      {user.lastLogin}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center">
                        <span className="text-sm text-gray-900 dark:text-gray-100 mr-4">{user.transactionCount} 笔</span>
                        {user.rating > 0 && (
                          <div className="flex items-center text-yellow-500">
                            {Array.from({ length: 5 }).map((_, i) => (
                              <i 
                                key={i} 
                                className={`fa-solid ${i < Math.floor(user.rating) ? 'fa-star' : 'fa-star-half-stroke'}`}
                                style={{ fontSize: '12px' }}
                              ></i>
                            ))}
                            <span className="text-xs text-gray-500 dark:text-gray-400 ml-1">
                              {user.rating}
                            </span>
                          </div>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={statusStyles[user.status].className}>
                        {statusStyles[user.status].text}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <div className="flex justify-end space-x-2">
                        <button
                          className="text-indigo-600 dark:text-indigo-400 hover:text-indigo-500 dark:hover:text-indigo-300"
                        >
                          <i className="fa-solid fa-eye mr-1"></i>查看
                        </button>
                        <button
                          className="text-blue-600 dark:text-blue-400 hover:text-blue-500 dark:hover:text-blue-300"
                        >
                          <i className="fa-solid fa-pen-to-square mr-1"></i>编辑
                        </button>
                        {user.id !== '2' && (
                          <button
                            onClick={() => changeUserStatus(user.id, user.status === 'active' ? 'inactive' : 'active')}
                            className="text-purple-600 dark:text-purple-400 hover:text-purple-500 dark:hover:text-purple-300"
                          >
                            <i className={`fa-solid ${user.status === 'active' ? 'fa-ban' : 'fa-check'} mr-1`}></i>
                            {user.status === 'active' ? '禁用' : '启用'}
                          </button>
                        )}
                        {user.id !== '2' && (
                          <button
                            onClick={() => deleteUser(user.id)}
                            className="text-red-600 dark:text-red-400 hover:text-red-500 dark:hover:text-red-300"
                          >
                            <i className="fa-solid fa-trash-can mr-1"></i>删除
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          
          {/* 分页 */}
          {filteredUsers.length > 0 && (
            <div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex items-center justify-between">
              <div className="hidden sm:flex sm:flex-1 sm:items-center sm:justify-between">
                <div>
                  <p className="text-sm text-gray-700 dark:text-gray-300">
                    显示 <span className="font-medium">{indexOfFirstItem + 1}</span> 到 <span className="font-medium">{Math.min(indexOfLastItem, filteredUsers.length)}</span> 条，共 <span className="font-medium">{filteredUsers.length}</span> 条记录
                  </p>
                </div>
                <div>
                  <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                    <button
                      onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                      disabled={currentPage === 1}
                      className={`relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 ${
                        currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''
                      }`}
                    >
                      <span className="sr-only">上一页</span>
                      <i className="fa-solid fa-chevron-left text-xs"></i>
                    </button>
                    
                    {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                      // 简单的分页逻辑，显示当前页附近的页码
                      let pageNum;
                      if (totalPages <= 5) {
                        pageNum = i + 1;
                      } else if (currentPage <= 3) {
                        pageNum = i + 1;
                      } else if (currentPage >= totalPages - 2) {
                        pageNum = totalPages - 4 + i;
                      } else {
                        pageNum = currentPage - 2 + i;
                      }
                      
                      return (
                        <button
                          key={pageNum}
                          onClick={() => setCurrentPage(pageNum)}
                          className={`relative inline-flex items-center px-4 py-2 border ${
                            currentPage === pageNum
                              ? 'bg-indigo-50 dark:bg-indigo-900/30 border-indigo-300 dark:border-indigo-700 text-indigo-700 dark:text-indigo-300'
                              : 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                          } text-sm font-medium`}
                        >
                          {pageNum}
                        </button>
                      );
                    })}
                    
                    <button
                      onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
                      disabled={currentPage === totalPages}
                      className={`relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 ${
                        currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''
                      }`}
                    >
                      <span className="sr-only">下一页</span>
                      <i className="fa-solid fa-chevron-right text-xs"></i>
                    </button>
                  </nav>
                </div>
              </div>
              
              {/* 移动端分页 */}
              <div className="flex items-center justify-between w-full sm:hidden">
                <p className="text-sm text-gray-700 dark:text-gray-300">
                  共 {filteredUsers.length} 条记录
                </p>
                <div className="flex space-x-2">
                  <button
                    onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                    disabled={currentPage === 1}
                    className={`px-3 py-1 border rounded text-sm ${
                      currentPage === 1
                        ? 'border-gray-300 dark:border-gray-600 bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-not-allowed'
                        : 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                    }`}
                  >
                    上一页
                  </button>
                  <button
                    onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
                    disabled={currentPage === totalPages}
                    className={`px-3 py-1 border rounded text-sm ${
                      currentPage === totalPages
                        ? 'border-gray-300 dark:border-gray-600 bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-not-allowed'
                        : 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                    }`}
                  >
                    下一页
                  </button>
                </div>
              </div>
            </div>
          )}
          
          {/* 空状态 */}
          {filteredUsers.length === 0 && (
            <div className="px-6 py-12 text-center">
              <div className="inline-flex items-center justify-center p-6 rounded-full bg-gray-100 dark:bg-gray-700 mb-4">
                <i className="fa-solid fa-user-slash text-3xl text-gray-400"></i>
              </div>
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">暂无用户数据</h3>
              <p className="text-gray-500 dark:text-gray-400">
                当前筛选条件下没有找到符合的用户
              </p>
              <button
                onClick={() => {
                  setSelectedRole('all');
                  setSelectedStatus('all');
                  setSearchQuery('');
                }}
                className="mt-4 px-4 py-2 rounded-lg text-sm font-medium bg-indigo-600 dark:bg-indigo-500 text-white hover:bg-indigo-700 dark:hover:bg-indigo-600"
              >
                重置筛选条件
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}